module jinji.user.api;

import jinji.common.query,
jinji.user.model,
jinji.user.service,
jinji.user.token;

/// 令牌有效期
enum tokenDuration = cast(ETime)(7 * 24 * 3600);

extern (C):

/// 登录
@"令牌"@type("string")
@Action void log(ref Request req, @"用户名" string user, @"密码" string pwd) {
	const u = findUser(user);
	// 登录
	checkPwd(u, pwd);

	exec!(SB.update!User.set("last_login=now(),log_times=log_times+1,status=$1")
			.where("id=$2"))(u.status, u.id);
	const token = createToken(u.id, u.perm, tokenDuration);
	login(req, token);
	req.send(signToken(token, u.pwd));
}

/// 令牌登录
@"用户信息"@type("[User, string | undefined]")
@Action void auth(ref Request req, @"令牌" string token) {
	Payload t = void;
	Id id;
	if (likely(has!User)) {
		t = parseToken(token);
	} else {
		id = initData();
		t = createToken(id, Perm.superadmin, tokenDuration);
	}
	login(req, t);
	{
		auto u = getUser!"id,name,perm"(req.uid);
		req.sendObj(u);
	}
	if (id) {
		const u = getUser!"pwd"(id);
		req.send(signToken(t, u.pwd));
	}
}

/// 注册
@"令牌"@type("string")
@Action void reg(ref Request req, @"用户名" string name, @"邮箱" string email, @"密码" string pwd) {
	if (unlikely(!has!User)) {
		initData();
	}
	const perm = cast(Perm)C.initialPerm;
	if (!perm)
		throw new InvalidOperationException(_("注册功能已关闭"));
	//checkCaptcha(req);
	const id = addUser(name, email, pwd, perm);
	const token = createToken(id, perm, tokenDuration);
	login(req, token);
	const u = getUser!"pwd"(id);
	req.send(signToken(token, u.pwd));
	//verifyMail(id, email);
}

mixin getObject!(User, "getUserInfo", "获取用户信息", "用户信息", "id");
